package com.kai.steering.data.service.service.impl;

import com.baomidou.mybatisplus.extension.api.R;
import com.kai.steering.common.vo.Result;
import com.kai.steering.common.web.vo.ReturnCodeExt;
import com.kai.steering.data.service.entity.domainObject.NoteDO;
import com.kai.steering.data.service.entity.domainObject.UserQuestionDO;
import com.kai.steering.data.service.entity.dto.NoteQueryDTO;
import com.kai.steering.data.service.entity.po.Note;
import com.kai.steering.data.service.entity.po.UserQuestion;
import com.kai.steering.data.service.entity.vo.NoteVO;
import com.kai.steering.data.service.mapper.NoteMapper;
import com.kai.steering.data.service.service.NoteService;
import com.kai.steering.common.web.service.impl.BaseServiceImpl;
import com.kai.steering.common.vo.Page;

import com.kai.steering.data.service.service.QuestionService;
import com.kai.steering.data.service.service.UserQuestionService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;

import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.bean.BeanUtil;

/**
 * <pre>
 * 笔记 服务实现类
 * </pre>
 *
 * @author kai
 * @since 2022-02-23
 */
@Slf4j
@Service
public class NoteServiceImpl extends BaseServiceImpl<NoteMapper, Note> implements NoteService {

    @Autowired
    private NoteMapper noteMapper;
    @Autowired
    private UserQuestionService userQuestionService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean saveNote(NoteDO noteDO) {
        /**
         * 验证参数
         */
        UserQuestionDO userQuestion= userQuestionService.getUserQuestionById( noteDO.getUserQuestionId());
        if (userQuestion==null|| StringUtils.isEmpty(userQuestion.getQuestionId())){
            throw ReturnCodeExt.PARAMETER_CHECK.getException("对象[" + userQuestion.getUserQuestionId() + "]为空");
        }
        /**
         * 构建对象
         */
        //用户对象
        noteDO.setUpdateDatetime(new Date());
        Note note = new Note(noteDO);
        /**
         * 调用服务
         */
        boolean save = super.save(note);
        noteDO.convertNoteDO(note);
        return save;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateNote(Serializable noteId, NoteDO noteDO) {
        /**
         * 验证参数
         */
        //id是否存在
        Note oldNote = super.getById(noteId);
        if (oldNote==null||oldNote.getNoteId()==null) {
            throw ReturnCodeExt.PARAMETER_CHECK.getException("对象[" + noteId + "]为空");
        }

        /**
         * 构建对象
         */
        Note newNot = new Note(noteDO);
        newNot.setNoteId(noteId.toString());
        newNot.setUpdateDatetime(new Date());
        newNot.setUserQuestionId(oldNote.getUserQuestionId());

        /**
         * 保存
         */
        boolean b = super.updateById(newNot);
        noteDO.convertNoteDO(newNot);
        return b;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteNote(Serializable id) {
        /**
         * 校验参数
         */
        Note oldNote = super.getById(id);
        if (oldNote==null||oldNote.getNoteId()==null) {
            throw ReturnCodeExt.PARAMETER_CHECK.getException("对象[" + id + "]为空");
        }

        return  super.removeById(id);
    }

    @Override
    public NoteDO getNoteById(Serializable noteId) {
        /**
         * 校验参数
         */
        Note note = super.getById(noteId);
        if (note==null||note.getNoteId()==null) {
            throw ReturnCodeExt.PARAMETER_CHECK.getException("对象[" + noteId + "]为空");
        }

        /**
         * 构建对象
         */
        NoteDO noteDO = new NoteDO(note);
        return noteDO;
    }

    @Override
    public List<NoteVO> getAllNote() {
        List<Note> notelist = noteMapper.selectList(new QueryWrapper<Note>());
        List<NoteVO> result = notelist.stream()
                .map(note -> {
                    NoteVO noteVo = new NoteVO();
                    BeanUtil.copyProperties(note, noteVo);
                    return noteVo;
                })
                .collect(Collectors.toList());
        return result;
    }

    @Override
        public Page<NoteVO> getNotePageList(NoteQueryDTO noteQueryDTO) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page page = setPageParam(
                noteQueryDTO, OrderItem.desc("create_time")
        );

        QueryWrapper<Note> queryWrapper = new QueryWrapper<>();

        //组合条件
        IPage<Note> entityPage = noteMapper.selectPage(page, queryWrapper);
        List<NoteVO> result = entityPage.getRecords().stream()
                .map(note -> {
                    NoteVO noteVo = new NoteVO();
                    BeanUtil.copyProperties(note, noteVo);
                    return noteVo;
                })
                .collect(Collectors.toList());

        return Page.<NoteVO>builder()
                .currPage(noteQueryDTO.getPageNo())
                .pageSize(noteQueryDTO.getPageSize())
                .totalCount((int) entityPage.getTotal())
                .list(result)
                .build();
    }


    @Override
    public boolean isExists(String key, String val, Serializable id) {
        QueryWrapper<Note> qw = new QueryWrapper<>();
        qw.eq(key, val);
        if (id != null) {
            qw.ne("id", id);
        }
        int num = this.count(qw);
        return num > 0;
    }
//
//    @Override
//    public NoteDO getNoteByQuestion(String questionId,String userId) {
//        QueryWrapper<Note> qw = new QueryWrapper<>();
//        qw.eq(key, questionId);
//
//        return null;
//    }

}

